package com.c7.bm.mybatis.service.impl;

import com.c7.bm.mybatis.model.C7Activity;
import com.c7.bm.mybatis.model.C7ActivityImageQr;
import com.c7.bm.mybatis.model.C7ActivityImages;
import com.c7.bm.mybatis.service.ActivityImageQrService;
import com.c7.bm.mybatis.service.ActivityImagesService;
import com.c7.bm.mybatis.util.FileUtil;
import com.c7.bm.mybatis.util.PageList;
import com.c7.bm.mybatis.util.PropertyReader;
import com.c7.bm.mybatis.util.ResponseWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.coobird.thumbnailator.Thumbnails;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * 活动图片实现类
 *
 * @author <a href="mailto:chenjunwen@xiaomagouche.com">Duke(陈俊文)</a>
 * @create 17/4/16  上午3:47
 */
@Service
public class ActivityImagesServiceImpl extends BaseService<C7ActivityImages> implements ActivityImagesService {

    @Autowired
    ActivityImageQrService imageQrService;

    /**
     * tomcat虚拟映射路径地址
     */
    private final static String rootPath = "/activity";

    @Override
    @Transactional
    public ResponseWrapper uploadImages(MultipartFile image, Long activityId) {
        ResponseWrapper responseWrapper = new ResponseWrapper();
        String imagePath = null;
        String fileName = null;
        String thumFileName = null;//缩略图
        String filePath = PropertyReader.get("imageFilePath", "file.properties");
        String ptFilePath = PropertyReader.get("activityFilePath", "file.properties");
        String activityImagePath = null;
        String activityThumPath = null;

        try {
            //首屏图片
            if (image != null && image.getSize() > 0) {
                imagePath = filePath + ptFilePath;
                fileName = FileUtil.getFileName(FileUtil.AT_NAME) + FileUtil.getSuffix(image);//大图文件名
                thumFileName = FileUtil.getFileName(FileUtil.THUM_NAME) + FileUtil.getSuffix(image);//缩略图文件名
//                FileUtil.uploadFiles(image, imagePath, fileName);
                Thumbnails.of(image.getInputStream()).scale(0.8f).toFile(imagePath + fileName);//大图
                Thumbnails.of(image.getInputStream()).scale(0.1f).toFile(imagePath + thumFileName);//缩略图
                activityImagePath = ptFilePath + fileName;//大图路径存入数据库
                activityThumPath = ptFilePath + thumFileName;//缩略图路径
                C7ActivityImages c7ActivityImages = new C7ActivityImages();
                c7ActivityImages.setActivityId(activityId);
                c7ActivityImages.setImagePath(rootPath + activityImagePath);
                c7ActivityImages.setThumPath(rootPath + activityThumPath);
                this.save(c7ActivityImages);
                responseWrapper.setStatus(0);
                responseWrapper.addAttribute("activityImages", c7ActivityImages);
            }
        } catch (Exception e) {
            responseWrapper.setStatus(1);
            responseWrapper.setMsg(e.toString());
        }
        return responseWrapper;
    }

    @Override
    public PageInfo<C7ActivityImages> getActivityImagesList(int page, int rows, Long activityId) {
        Example example = new Example(C7ActivityImages.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id DESC");
        if (activityId != null) {
            criteria.andEqualTo("activityId", activityId);
        }

        PageHelper.startPage(page, rows);
        List<C7ActivityImages> list = this.selectByExample(example);
        PageInfo<C7ActivityImages> pageInfo = new PageInfo<>(list);
        if (page > pageInfo.getPages()) {
            pageInfo.setList(null);
        }
        return pageInfo;
    }

    @Override
    public List<C7ActivityImages> getAllImagesList(Long activityId) {
        Example example = new Example(C7ActivityImages.class);
        Example.Criteria criteria = example.createCriteria();
        if (activityId != null) {
            criteria.andEqualTo("activityId", activityId);
        }
        return this.selectByExample(example);
    }

    @Override
    public ResponseWrapper generateImageQr(Long imageId, String linkValue) {
        ResponseWrapper responseWrapper = new ResponseWrapper();
        try {
            C7ActivityImages c7ActivityImages = this.selectByKey(imageId);
            if (c7ActivityImages == null) {
                responseWrapper.setStatus(1);
            }
            String fileName = FileUtil.getFileName(FileUtil.QR_NAME) + ".jpg";
            String filePath = PropertyReader.get("imageFilePath", "file.properties")
                    + PropertyReader.get("qrFilePath", "file.properties");
            String qrPath = null;
            if (linkValue != null && !"".equals(linkValue)) {
                ByteArrayOutputStream out = QRCode.from(linkValue).to(ImageType.PNG).withSize(1024, 1024).stream();
                FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath + fileName));

                fileOutputStream.write(out.toByteArray());

                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                qrPath = rootPath + PropertyReader.get("qrFilePath", "file.properties") + fileName;
            } else {
                qrPath = null;
            }


            Example example = new Example(C7ActivityImageQr.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("activityImageId", imageId);
            List<C7ActivityImageQr> list = imageQrService.selectByExample(example);

            if (list.size() > 0) {
                C7ActivityImageQr imageQr = list.get(0);
                imageQr.setActivityImageId(imageId);
                imageQr.setQrImagePath(qrPath);
                imageQr.setLinkValue(linkValue);
                imageQrService.updateAll(imageQr);
            } else {
                C7ActivityImageQr imageQr = new C7ActivityImageQr();
                imageQr.setActivityImageId(imageId);
                imageQr.setQrImagePath(qrPath);
                imageQr.setLinkValue(linkValue);
                imageQrService.save(imageQr);
            }

            responseWrapper.setStatus(0);
            return responseWrapper;
        } catch (Exception e) {
            responseWrapper.setStatus(1);
            responseWrapper.setMsg(e.toString());
            return responseWrapper;
        }
    }

    public static void main(String[] args) {
        String url = "http://120.132.23.97/bm/getActivityList";
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Accept", "application/json");
        requestHeaders.set("Content-Type", "application/json");

        String jsonStr = "";

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> httpEntity = new HttpEntity<String>(jsonStr, requestHeaders);
        String jsonData = restTemplate.postForObject(url, httpEntity, String.class);

        System.out.println(jsonData);
    }

}
